package com.noah.bee.core.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtils {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
	private static int connectTimeout=1*60*1000;
	private static int readTimeout=1*60*1000;

	public static Object callJsonRpcPost(String url, Class<?> responseClass, Object requesparams)throws Exception {
		return callJsonRpc(url, responseClass, requesparams, "POST",null);
	}

	public static Object callJsonRpc(String url, Class<?> responseClass, Object requesparams, String type,String charSet) throws Exception{
		URL targeturl;
		PrintWriter out =null;
		try {
			targeturl = new URL(url);
			URLConnection connection = targeturl.openConnection();
			HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setRequestMethod(type);
			httpURLConnection.setRequestProperty("Content-Type", "application/json");
			httpURLConnection.setConnectTimeout(connectTimeout);
			httpURLConnection.setReadTimeout(readTimeout);
			ObjectMapper mapper = new ObjectMapper(); // from org.codeahaus.jackson.map
			if (requesparams != null) {
				// 获取URLConnection对象对应的输出流
	            out = new PrintWriter(httpURLConnection.getOutputStream());
	            // 发送请求参数
	            out.print(requesparams);
	            // flush输出流的缓冲
	            out.flush();
			}
			InputStream inputStream = httpURLConnection.getInputStream();

			if (responseClass.getName().equals(byte.class.getName())) {
				byte[] bytes = IOUtils.toByteArray(inputStream);
				return bytes;
			}
			String responseString = "";
			if(charSet == null){
				responseString =new String(IOUtils.toByteArray(inputStream),"UTF-8");
			}else{
				responseString =new String(IOUtils.toByteArray(inputStream),charSet);
			}
			LOGGER.info("response is:{}",responseString);
			if (responseClass.getName().equals(String.class.getName())) {
				return responseString;
			} else if (responseClass.getName().equals(JsonNode.class.getName())) {
				return mapper.readTree(responseString);
			} else {
				Object response = mapper.readValue(responseString, responseClass);
				return response;
			}

		} catch (Exception e) {
			LOGGER.error("http request server error",e);
			throw e;
			
		}finally{
			if(out!=null){
				out.close();
			}
			
		}
		
	}
}
